package leetcode;

/**
 * 字符串转换整数 (atoi) 
 */
public class LeetCode8 {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        String res = "";
        char fisrtNotEmpty = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == ' ' && fisrtNotEmpty == 0) {
                continue;
            }
            if (fisrtNotEmpty == 0) {
                if (!(isDig(c) || isOp(c))) {
                    return 0;
                }
                fisrtNotEmpty = c;
            } else if (!isDig(c)) {
                break;
            }
            res = res + c;
        }
        if (res.length() == 0 || (res.length() == 1 && isOp(fisrtNotEmpty))) {
            return 0;
        }
        long resLong = Long.valueOf(res);
        if (resLong > Integer.MAX_VALUE) {
            resLong = Integer.MAX_VALUE;
        } else if (resLong < Integer.MIN_VALUE) {
            resLong = Integer.MIN_VALUE;
        }
        return (int) resLong;
    }

    private boolean isDig(char c) {
        return (c >= '0' && c <= '9');
    }

    private boolean isOp(char c) {
        return c == '+' || c == '-';
    }

    public static void main(String[] args) {
        LeetCode8 leetCode08 = new LeetCode8();
        System.out.println(leetCode08.myAtoi("42"));
    }
}
